package com.handu.luna.core.domain.promotion;

import java.util.Date;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.handu.luna.core.domain.BaseRepository;

public interface SalesPromotionGoodsRepository extends JpaRepository<SalesPromotionGoods,Long>,BaseRepository<SalesPromotionGoods>,JpaSpecificationExecutor<SalesPromotionGoods> {
	
	@Query("from SalesPromotionGoods s  where s.salesPromotionId = :salesPromotionId")
	Page<SalesPromotionGoods> findBySalesPromotionId(@Param("salesPromotionId") long salesPromotionId,Pageable pageable);

	/*@Query("from SalesPromotionGoods s  where s.salesPromotionId = :salesPromotionId AND goodsId = :goodsId ")
	List<SalesPromotionGoods> findBySalesPromotionIdAndGoodsId(@Param("salesPromotionId") long salesPromotionId,@Param("goodsId") long goodsId);
*/
	@Modifying
	@Query("delete from SalesPromotionGoods s  where s.salesPromotionId = :salesPromotionId")
	public void deleteByPromotionId(@Param("salesPromotionId") int salesPromotionId);
	
	@Modifying
	@Query("delete from SalesPromotionGoods s  where s.salesPromotionId = :salesPromotionId and s.goodsId = :goodsId")
	public void deleteByPromotionIdAndGoodsId(@Param("salesPromotionId") int salesPromotionId,@Param("goodsId") long goodsId);
	
	
	@Query("select s2 from SalesPromotion s2 " +
            "where s2.beginTime <= ?2 and s2.endTime >= ?2 and " +
            "s2.id in (select s.salesPromotionId from SalesPromotionGoods s where s.goodsId = ?1) order by s2.createdDate desc")
	Page<SalesPromotion> findUniqueSalesPromotionByGoodsId(long goodsId, Date date,Pageable pageable);
	
	
    /***********************************商品详情页---开始*************************************************/

    @Query("select s2 from SalesPromotion s2 " +
            "where s2.beginTime <= ?2 and s2.endTime >= ?2 and " +
            "s2.id in (select s.salesPromotionId from SalesPromotionGoods s where s.goodsId = ?1)  order by s2.createdDate desc")
    List<SalesPromotion> findCurrentSalesPromotionByGoodsId(long goodsId, Date date);

    @Query("from SalesPromotionGoods s  where s.salesPromotionId = ?1 AND goodsId = ?2")
    SalesPromotionGoods findBySalesPromotionIdAndGoodsId(long salesPromotionId, long goodsId);

    /************************************商品详情页---结束*************************************************/
}
